from ctypes import *
from telnetlib import PRAGMA_HEARTBEAT
import win32gui
import win32api
import win32con
import os
from time import sleep
username = '12345678'
tuple(username)
userkey = 'xxxxx'
tuple(userkey)


def Easyconnect():
    '''打开应用'''
    dir = "C:\\Program Files (x86)\\Sangfor\\SSL\\SangforCSClient\\SangforCSClient.exe"
    os.startfile(dir)
    sleep(7)


def setpos(h):
    '''根据句柄设置鼠标坐标至窗体中央'''
    left, top, right, bottom = win32gui.GetWindowRect(h)
    pos = [int((left + right)/2), int((top + bottom)/2)]
    win32api.SetCursorPos(pos)


def get_son_windows(parent):
    hWnd_child_list = []
    win32gui.EnumChildWindows(
        parent, lambda hWnd, param: param.append(hWnd), hWnd_child_list)
    return hWnd_child_list


def mouse():
    '''模拟鼠标点击'''
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,
                         0, 0, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,
                         0, 0, 0, 0)
    sleep(0.08)


def keyboard(val):
    '''模拟键盘点击'''
    win32api.keybd_event(val, 0, 0, 0)
    win32api.keybd_event(val, 0, win32con.KEYEVENTF_KEYUP, 0)
    sleep(0.08)


def inputchar(blank):
    for c in blank:
        if (c == '@'):
            win32api.keybd_event(16, 0, 0, 0)
            win32api.keybd_event(50, 0, 0, 0)
            win32api.keybd_event(50, 0, win32con.KEYEVENTF_KEYUP, 0)
            win32api.keybd_event(16, 0, win32con.KEYEVENTF_KEYUP, 0)
        c = ord(c)
        if ('a' <= chr(c) <= 'z'):
            c -= 32
        keyboard(c)


'''核心在这，感动'''
hwnd_title = dict()


def get_all_hwnd(hwnd, a):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})


def get_handle():
    win32gui.EnumWindows(get_all_hwnd, 0)
    for h, t in hwnd_title.items():
        if (t == "EasyConnect"):
            return h
            break


if __name__ == "__main__":
    Easyconnect()
    ec_handle = get_handle()
    sonlist = get_son_windows(ec_handle)
    for i, h in enumerate(sonlist):

        if (i == 22):
            setpos(h)
            mouse()
            inputchar(username)
        elif (i == 24):
            setpos(h)
            mouse()
            inputchar(userkey)
            keyboard(13)
            break
